package com.fe.class03;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Description 用栈结构实现队列结构
 * @Author sosuke :-)
 * @Date 2021/12/12 06:16
 */
public class Code08_TwoStacksToQueue {

    /**
     * 1. push栈向pop栈倒数据，要一次性倒完
     * 2. 如果pop栈中有数据，则push栈不能倒数据
     */
    public static class TwoStackToQueue {
        private Stack<Integer> pushStack;// 用于入队
        private Stack<Integer> popStack;// 用于出队

        public TwoStackToQueue() {
            this.pushStack = new Stack<>();
            this.popStack = new Stack<>();
        }

        public void offer(int data) {
            pushStack.push(data);
            pushToPop();// 此处也可以不倒数据
        }

        public int poll() {
            if (pushStack.isEmpty() && popStack.isEmpty()) {
                throw new RuntimeException("Queue is empty");
            }
            pushToPop();
            return popStack.pop();
        }

        public int peek() {
            if (pushStack.isEmpty() && popStack.isEmpty()) {
                throw new RuntimeException("Queue is empty");
            }
            pushToPop();
            return popStack.peek();
        }

        /**
         * push栈向pop栈倒数据
         */
        private void pushToPop() {
            if (popStack.isEmpty()) {
                while (!pushStack.isEmpty()) {
                    popStack.push(pushStack.pop());
                }
            }
        }

        public static void main(String[] args) {
            int testTimes = 100000;
            int maxValue = 1000;
            int oneTestNums = 100;
            for (int i = 0; i < testTimes; i++) {
                TwoStackToQueue twoStackToQueue = new TwoStackToQueue();
                Queue<Integer> queue = new LinkedList<>();
                for (int j = 0; j < oneTestNums; j++) {
                    int numQueue = (int) (Math.random() * maxValue);
                    if (queue.isEmpty()) {
                        queue.offer(numQueue);
                        twoStackToQueue.offer(numQueue);
                    } else {
                        if (Math.random() < 0.5) {
                            queue.offer(numQueue);
                            twoStackToQueue.offer(numQueue);
                        } else {
                            if (!isEqual(queue.poll(), twoStackToQueue.poll())) {
                                System.out.println("TwoStackToQueue oops");
                            }
                        }
                    }
                }
            }
            System.out.println("Nice");
        }

        private static boolean isEqual(Integer o1, Integer o2) {
            if (null == o1 && null != o2) return false;
            if (null != o1 && null == o2) return false;
            if (null == o1) return true;
            return o1.equals(o2);
        }
    }
}
